package com.innovation.ic.sc.base.thread.listener.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.innovation.ic.sc.base.pojo.constant.handler.RabbitMqConstants;
import com.innovation.ic.sc.base.service.sc.MyCompanyCurrencyService;
import com.innovation.ic.sc.base.vo.CompanyCurrencyVo;
import com.rabbitmq.client.*;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 删除我的公司币种
 */
public class ListenAddCompanyCurrencyQueueThread extends AbstractRabbitmqThread implements Runnable {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Channel channel;
    private MyCompanyCurrencyService myCompanyCurrencyService;

    public ListenAddCompanyCurrencyQueueThread(Channel channel, MyCompanyCurrencyService myCompanyCurrencyService) {
        this.channel = channel;
        this.myCompanyCurrencyService = myCompanyCurrencyService;
    }

    @SneakyThrows
    public void run() {
        String exchange = RabbitMqConstants.SC_ERP_EXCHANGE;
        String routingKey = RabbitMqConstants.ERP_SC_CURRENCY_ADD;
        final String queue = routingKey;
        channel.queueBind(queue, exchange, routingKey);
        channel.queueDeclare(queue, true, false, false, null);
        channel.exchangeDeclare(exchange, RabbitMqConstants.DIRECT_TYPE, true);
        Consumer callback = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                String bodyString = new String(body);
                logger.info("添加我的公司币种, 接收到的队列:[{}]的消息为:[{}]", queue, bodyString);
                try {
                    if (!Strings.isNullOrEmpty(bodyString)) {
                        // 获取消息体中的数据内容
                        String messageBody = getMessageBody(bodyString);
                        if (!Strings.isNullOrEmpty(messageBody)) {
                            CompanyCurrencyVo companyCurrencyVo = JSONObject.parseObject(messageBody, CompanyCurrencyVo.class);
                            myCompanyCurrencyService.listenAddCompanyCurrency(companyCurrencyVo);
                        }
                    }
                } catch (Exception e) {
                    logger.error("监听队列:[{}]时出现问题,原因:", queue, e);
                }
            }
        };
        channel.basicConsume(queue, true, callback);
    }
}